package com.example.semo.controller;

import com.example.semo.dao.UserDao;
import com.example.semo.entity.User;
import com.example.semo.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
//当前控制器跨域
//@CrossOrigin
//控制器
@Controller
@ResponseBody
public class UserController {
    String msg;
    int code;
    //自动注入
    @Autowired
    UserDao userDao;
    //请求路径
    @RequestMapping("/login")
    //登录
    public JsonResult login(@RequestBody User user){
        System.out.println("当前登录用户名"+user.getUserName());
        List list = userDao.Login(user);
        if(null == list || list.size()==0){
            code=500;
            msg="用户名或密码错误";
        }else{
            System.out.println("用户名是："+user.getUserName());
            String logTime= LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            System.out.printf(logTime);
            user.setLogTime(logTime);
            int sum=userDao.LogTime(user);
            code=200;
            msg="登录成功,欢迎回来";
        }
        return new JsonResult(code,msg, list);
    }
    //注册
    @RequestMapping("/reg")
    public JsonResult reg(@RequestBody User user){
        System.out.println("当前注册用户名："+user.getUserName());
        List list= userDao.RegSelect(user);
        if(null==list||list.size()==0){
            String regTime= LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            System.out.printf(regTime);
            user.setRegTime(regTime);
            int sum= userDao.Reg(user);
            msg="注册成功";
            code=200;
        }else {
            msg="用户名已存在";
            code=500;
        }
        return new JsonResult(code,msg,null);
    }
    //查询所有用户
    @RequestMapping("/selectUser")
    public JsonResult selectUser(){
        List list = userDao.SelectUser();
        if(null == list || list.size()==0){
            code=500;
            msg="数据为空";
        }else{
            code=200;
            msg="查询用户列表成功";
        }
        return new JsonResult(200,msg, list);
    }
}
